<template>
	<view class="content">
		<!-- https://demo.z-paging.zxlee.cn/#/ -->
		<global-notify></global-notify>
		<view style="flex-grow: 1;">
			<z-paging :fixed='false' autoShowBackToTop show-refresher-update-time ref="paging" :auto="false"
				v-model="dataList" @query="queryList">
				<u-sticky style="top: 0">
					<view class="topTab">
						<u-tabs :current='currentIndex' style="width: 100%" :scrollable='false' :list="tabs"
							@click="changeTag"></u-tabs>
					</view>
					<view style="background-color: #fff;padding: 8px;border-bottom: 1px solid #F3F5F9;">
						<u-search :clearabled="true" @clickIcon='search' @custom="search" @clear="search" @search='search'
							placeholder="请输入班次关键词" v-model="searchKey"></u-search>
					</view>
				</u-sticky>

				<!-- 自定义返回顶部view -->
				<template #backToTop>
					<self-back-to-top ref="backToTop" :current="currentNo" :total="total" />
				</template>

				<view class="listItem" v-for="(item,index) in dataList" :key="index">
					<view class="listItemName">
						<view>
							<span v-if='item.undertake' class="undertakeIcon"></span>{{item.planName}}
						</view> <u-tag :text="getTagLable(item)" plain size="mini"></u-tag>
					</view>
					<view class="listItemInfo">
						<view class="listItemInfoLabel">开始时间：</view>
						<view class="listItemInfoValue">{{item.beginDate}}</view>
					</view>
					<view class="listItemInfo">
						<view class="listItemInfoLabel">结束时间：</view>
						<view class="listItemInfoValue">{{item.endDate}}</view>
					</view>
					<view class="listItemInfo">
						<view class="listItemInfoLabel">时间段：</view>
						<view class="listItemInfoValue">
							{{(item.timeRanges || []).map(range => range.beginHour + ' - ' + range.endHour).join("、")}}
						</view>
					</view>
					<template v-if="['to_be_published', 'published'].indexOf(selectTab.value) >= 0">
						<!-- <view class="listItemInfo">
						<view class="listItemInfoLabel">手动排班：</view>
						<view class="listItemInfoValue">{{item.distributional?'是':'否'}}</view>
					</view> -->
						<template v-if="item.distributional">
							<!-- 手动排班 -->
							<view class="listItemInfo">
								<view class="listItemInfoLabel">当前总人数：</view>
								<view class="listItemInfoValue">
									<view class="flex">{{item.currentNum}}
										<u-icon customStyle="margin: 0 4px" name='man-add-fill' size='18'
											v-if="['to_be_published', 'published'].indexOf(selectTab.value) >= 0" @click="addPerson(item)"
											color="#2979ff"></u-icon>
									</view>
								</view>
							</view>
						</template>
						<template v-else>
							<view class="flex wrap">
								<view style="flex: 1" class="listItemInfo">
									<view class="listItemInfoLabel">抢班人数：</view>
									<view class="listItemInfoValue">
										<view class="flex">{{item.grabbingNum}}
											<u-icon customStyle="margin: 0 4px" name='edit-pen-fill' size='18'
												v-if="'to_be_published' == selectTab.value" @click="modifyGrabbingNum(item)"
												color="#fa3534"></u-icon>
										</view>
									</view>
								</view>
								<view style="flex: 1" class="listItemInfo">
									<view class="listItemInfoLabel">当前总人数：</view>
									<view class="listItemInfoValue">
										<view class="flex">{{item.currentNum}}
											<u-icon customStyle="margin: 0 4px" name='man-add-fill' size='18'
												v-if="['to_be_published', 'published'].indexOf(selectTab.value) >= 0" @click="addPerson(item)"
												color="#2979ff"></u-icon>
										</view>
									</view>
								</view>
							</view>

						</template>

					</template>

					<template v-if="'to_be_published' == selectTab.value">
						<u-divider text="分割线" :dot="true"></u-divider>
						<view class="listItemBtns">
							<u-button @click="viewPlan(item, true)" size='small' customStyle="margin: 0 5px"
								type="primary">详情</u-button>
							<u-button @click="publishPlan(item)" size='small' customStyle="margin: 0 5px" type="warning">发布</u-button>
							<u-button @click="closePlan(item)" size='small' customStyle="margin: 0 5px" type="error">关闭</u-button>

						</view>
					</template>
					<template v-else-if="'published' == selectTab.value">
						<u-divider text="分割线" :dot="true"></u-divider>
						<view class="listItemBtns">
							<u-button @click="viewPlan(item, true)" size='small' customStyle="margin: 0 5px"
								type="primary">详情</u-button>
							<u-button @click="closePlan(item)" size='small' customStyle="margin: 0 5px" type="error">关闭</u-button>
						</view>
					</template>
					<template v-else-if="'bookable' == selectTab.value">
						<view class="listItemInfo">抢班进度：{{item.currentNum}}/{{item.grabbingNum}}</view>
						<view>
							<u-line-progress customStyle="margin-top: 5px" :percentage="getPercent(item)"
								activeColor="#ff0000"></u-line-progress>
						</view>
						<u-divider text="分割线" :dot="true"></u-divider>
						<view class="listItemBtns">
							<u-button :disabled="item.remainder <= 0" @click="grabbingPlan(item)" size='small'
								type="primary">预约</u-button>
						</view>
					</template>
					<template v-else-if="'history' == selectTab.value">

						<u-divider text="分割线" :dot="true"></u-divider>
						<view class="listItemBtns">
							<u-tag plain type='info' v-if="item.canceled" text="预约已取消"></u-tag>
							<u-tag plain v-else-if="item.status == 'canceled'" text="班次已关闭" type='info'></u-tag>
							<u-tag plain v-else-if="item.status == 'finished'" text="班次已结束" type='info'></u-tag>
							<u-button v-else :disabled="!item.cancellation" @click="cancelReservationPlan(item)" size='small'
								type="error">取消预约</u-button>
						</view>
					</template>
				</view>
			</z-paging>


			<!-- 修改抢班人数 -->
			<u-modal :show="showGrabbingModal" showCancelButton :title="`修改 ${selectPlan.planName} 抢班人数`"
				@cancel="()=>{showGrabbingModal=false}" @confirm="confirmGrabbing">
				<slot>
					<view style="    width: 100%;text-align: left;">
						<u--form :error-type="'message'" labelPosition="left" labelWidth='80' :model="grabbingNumForm"
							:rules="rulesGrabbingNum" ref="grabbingNumForm">
							<u-form-item label="抢班人数" prop="grabbingNum">
								<u-number-box integer v-model="grabbingNumForm.grabbingNum" :min="0" :step="1"></u-number-box>
								<!-- <u--input placeholder="请输入抢班人数" type='digit' v-model="grabbingNumForm.grabbingNum"></u--input> -->
							</u-form-item>
						</u--form>
					</view>
				</slot>
			</u-modal>

			<!-- 关闭班次提醒 -->
			<u-modal :show="showCloseModal" showCancelButton :title="`关闭 ${selectPlan.planName} `"
				@cancel="()=>{showCloseModal=false}" @confirm="confirmClose">
				<slot>
					<view style="width: 100%;text-align: left;">
						<u--form :borderBottom='true' :error-type="'message'" labelPosition="left" labelWidth='0' :model="closeForm"
							:rules="rulesCloseForm" ref="closeForm">
							<u-form-item :borderBottom='true' label="" prop="reason">
								<u--textarea placeholder="请输入关闭理由" count v-model="closeForm.reason"></u--textarea>
							</u-form-item>
						</u--form>
					</view>
				</slot>
			</u-modal>

			<!-- 发布班次参数框 -->
			<u-modal :show="showPublishModal" showCancelButton :title="`发布 ${selectPlan.planName} `"
				@cancel="()=>{showPublishModal=false}" @confirm="confirmPublish">
				<slot>
					<view style="width: 100%;text-align: left;">
						<view v-if="selectPlan.distributional">
							<u-alert type="warning" :title="`当前班次总人数为${selectPlan.currentNum},请确认是否发布！`"></u-alert>
						</view>
						<view v-else>
							<u-alert type="warning" :title="`当前班次抢班人数为${selectPlan.grabbingNum},请确认是否发布！`"></u-alert>
						</view>
						<u--form :borderBottom='true' :error-type="'message'" labelPosition="left" labelWidth='80'
							:model="publishForm" :rules="rulesPublishForm" ref="publishForm">
							<u-form-item label="发布方式" prop="publishType">
								<u-radio-group v-model="publishForm.publishType" @change="() => {publishForm.publishTime = null}">
									<u-radio label="即刻发布" name="IMMEDIATE_RELEASE">
									</u-radio>
									<u-radio :customStyle="{marginLeft: '8px'}" label="延时发布" name="DELAYED_RELEASE">
									</u-radio>
								</u-radio-group>
							</u-form-item>

							<u-form-item v-if="publishForm.publishType == 'DELAYED_RELEASE'" @click="showDate" label="发布时间"
								prop="publishTime">
								<u--input readonly customStyle="width: 100%" @click="showDate" v-model="publishForm.publishTime"
									placeholder="请选择发布时间" border="none"></u--input>
								<u-icon slot="right" name="arrow-right"></u-icon>
								<u-datetime-picker :minDate="minDate" @cancel="cancelDate" ref="datetimePicker" :show="showPublishTime"
									@confirm='confirmDate' v-model="selectTime" mode="datetime"></u-datetime-picker>
							</u-form-item>
						</u--form>
					</view>
				</slot>
			</u-modal>

			<!-- 预约班次确认框 -->
			<u-modal :show="showBookingModal" showCancelButton title="预约班次" confirmText='预约'
				@cancel="()=>{showBookingModal=false}" @confirm="confirmBooking">
				<slot>
					<view style="width: 100%;text-align: left;">
						<u-cell-group>
							<u-cell title="班次名称" :value="selectPlan.planName"></u-cell>
							<u-cell title="开始时间" :value="selectPlan.beginDate"></u-cell>
							<u-cell title="结束时间" :value="selectPlan.endDate"></u-cell>
							<u-cell title="时间段"
								:value="(selectPlan.timeRanges || []).map(range => range.beginHour + ' - ' + range.endHour).join('、')"></u-cell>
						</u-cell-group>
					</view>
				</slot>
			</u-modal>

			<!-- 取消预约框 -->
			<u-modal :show="showReservationModal" showCancelButton :title="`取消预约 ${selectPlan.planName} `"
				@cancel="()=>{showReservationModal=false}" @confirm="confirmReservation">
				<slot>
					<view style="width: 100%;text-align: left;">
						<u--form :borderBottom='true' :error-type="'message'" labelPosition="left" labelWidth='0'
							:model="reservationForm" :rules="rulesReservationForm" ref="reservationForm">
							<u-form-item :borderBottom='true' label="" prop="reason">
								<u--textarea placeholder="请输入取消理由" count v-model="reservationForm.reason"></u--textarea>
							</u-form-item>
						</u--form>
					</view>
				</slot>
			</u-modal>

			<!-- 发布确认框 -->
			<u-modal :show="showPublishPreModal" showCancelButton title="确认发布" :content='publishPreMsg'
				@cancel="()=>{showPublishPreModal=false}" @confirm="confirmPublishPre"></u-modal>

			<!-- 班次详情窗口 -->
			<u-action-sheet :round='10' :show="showPlanModal" title="班次详情" @close="()=>{showPlanModal=false}">
				<slot>
					<view style="width: 100%;text-align: left; ">
						<u-tabs :scrollable='false'
							:list="[{name: '基础信息', value:'base'}, {name: '律师信息', value: 'lawyers'}, {name: '操作记录', value: 'log'}]"
							@click="(item) => {currentTab = item}"></u-tabs>

						<view style="max-height: 60vh; overflow-y: auto;">
							<view v-if="currentTab.value == 'base'">
								<u-cell-group>
									<u-cell title="班次名称" :value="selectPlan.planName"></u-cell>
									<u-cell title="所属项目" :value="getProjectName(selectPlan.projectId)"></u-cell>
									<u-cell title="班次类型" :value="getICType(selectPlan.schedulingPlanType)"></u-cell>
									<u-cell title="是否兜底班次" :value="selectPlan.undertake?'是':'否'"></u-cell>
									<u-cell title="是否手动排班" :value="selectPlan.distributional?'是':'否'"></u-cell>
									<u-cell title="开始时间" :value="selectPlan.beginDate"></u-cell>
									<u-cell title="结束时间" :value=" selectPlan.endDate"></u-cell>
									<u-cell title="班次时间段"
										:value="(selectPlan.timeRanges || []).map(item => item.beginHour + ' - ' + item.endHour).join('、')"></u-cell>
									<u-cell v-if="!selectPlan.distributional" title="抢班律师标签"
										:value="(selectPlan.lawyerTagNames || []).join('、')"></u-cell>
								</u-cell-group>
							</view>

							<view v-else-if="currentTab.value == 'lawyers'">
								<view v-if="selectPlan.planRecruitMappings && selectPlan.planRecruitMappings.length > 0">
									<u-list>
										<u-list-item v-for="planRecruitMapping in (selectPlan.planRecruitMappings || [])"
											:key="planRecruitMapping.id">
											<u-cell>
												<u-avatar slot="icon" shape="square" size="35"
													:src="planRecruitMapping.lawyerInfo.user.avatar"></u-avatar>

												<template slot="title">
													<view class="flex">
														<u-tag size="mini" plainFill plain
															:color="planRecruitMapping.lawyerInfo.user.disabled?'#fa3534':'#2979ff'"
															:borderColor="planRecruitMapping.lawyerInfo.user.disabled?'#fa3534':'#2979ff'"
															:text="planRecruitMapping.lawyerInfo.user.disabled? '禁用':'正常'"></u-tag>
														<view style="margin-left: 4px;">
															{{planRecruitMapping.lawyerInfo?planRecruitMapping.lawyerInfo.lawyerName: ''}}
														</view>
													</view>
												</template>
												<template slot="value">
													<u-icon size="18" color='#fa3534' name="trash-fill"
														@click="deleteMapping(planRecruitMapping)">
													</u-icon>
												</template>
												<template slot="label">
													<u--text :size='12' :text="planRecruitMapping.remark"></u--text>
												</template>
											</u-cell>
										</u-list-item>
									</u-list>

								</view>
								<u-empty v-else mode="list"></u-empty>
							</view>

							<view v-else-if="currentTab.value == 'log'">
								<u-cell v-for="log in (selectPlan.logs || [])" :key="log.id" :title="log.whenCreated"
									:label="log.remark"></u-cell>
							</view>
						</view>
					</view>
				</slot>
			</u-action-sheet>

			<!-- 删除律师确认框 -->
			<u-modal :show="showDelMappingModal" showCancelButton title="确认删除" @cancel="()=>{showDelMappingModal=false}"
				@confirm="confirmDelMapping">
				<slot>
					请确认是否删除班次{{selectPlan.planName}}下的律师{{mapping.lawyerInfo?mapping.lawyerInfo.lawyerName: ''}}?
				</slot>
			</u-modal>

			<!-- 添加律师操作框 -->
			<u-action-sheet :round='10' :show="showLawyerModal" title="添加律师"
				@close="()=>{showLawyerModal=false; searchKeyL=''}">
				<slot>
					<view style="width: 100%;text-align: left; height: 85vh; background-color: #F3F5F9;">
						<z-paging v-if="showLawyerModal" :fixed="false" ref="lawyerPaging" :auto="false" v-model="lawyerList"
							@query="queryLawyerList">
							<!-- 需要固定在顶部不滚动的view放在slot="top"的view中，如果需要跟着滚动，则不要设置slot="top" -->
							<u-sticky style="top: 0">
								<view
									style="background-color: #fff;padding: 8px;border-top: 1px solid #F3F5F9; border-bottom: 1px solid #F3F5F9;">
									<u-search :clearabled="true" @clickIcon='searchL' @custom="searchL" @clear="searchL" @search='searchL'
										placeholder="请输入律师名称关键词" v-model="searchKeyL"></u-search>
								</view>
								<view style="background-color: #fff" v-if="selectedLawyers && selectedLawyers.length > 0">
									<u-divider customStyle="margin: 0; padding-top: 8px;" textPosition="left"
										:text="`当前已选择【${selectedLawyers.length}】`" :hairline="true"></u-divider>
									<view class="flex wrap" style="padding: 5px 10px;">
										<u-tag plain plainFill :key="selectedLawyer.id" :name="selectedLawyer.id" @close="closeSelect"
											closable color="primary" :text="selectedLawyer.lawyerName"
											v-for="selectedLawyer in selectedLawyers"></u-tag>
									</view>
									<u-divider customStyle="margin: 0; padding-top: 8px;" :hairline="true"></u-divider>
									<view style="padding: 5px; text-align: right;">
										<u-button size="small" type="warning" @click="saveLawyer">确定 </u-button>
									</view>
								</view>
							</u-sticky>

							<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
							<view class="listItem" v-for="(item,index) in lawyerList" :key="index">
								<view class="listItemName">
									<view class="flex">
										<view class="flex" style="width: flex-grow: 1;">
											<u-tag size="mini" plainFill plain :color="item.user.disabled?'#fa3534':'#2979ff'"
												:borderColor="item.user.disabled?'#fa3534':'#2979ff'"
												:text="item.user.disabled? '禁用':'正常'"></u-tag>
											<view style="margin-left: 4px;">
												{{item.lawyerName}}
											</view>
										</view>
										<view style="min-width: max-content;">
											<u--text :color="(selectedLawyers.filter(l => l.id == item.id) || []).length > 0?'#f90':'#2979ff'"
												:size='14' @click="chooseLawyer(item)"
												:text="(selectedLawyers.filter(l => l.id == item.id) || []).length > 0? '取消':'选择'"></u--text>
										</view>
									</view>
								</view>
								<view class="flex">
									<view class="listItemInfo">
										<view class="listItemInfoLabel">工号：</view>
										<view class="listItemInfoValue">{{item.userNo}}</view>
									</view>
									<view class="listItemInfo">
										<view class="listItemInfoLabel">联系方式：</view>
										<view class="listItemInfoValue">{{item.lawyerMobile}}</view>
									</view>
								</view>
								<view class="flex">
									<view class="listItemInfo">
										<view class="listItemInfoLabel">执业证号码：</view>
										<view class="listItemInfoValue">{{item.licenseNumber}}</view>
									</view>
									<view class="listItemInfo">
										<view class="listItemInfoLabel">执业时间：</view>
										<view class="listItemInfoValue">
											{{item.startWorkDate}}
										</view>
									</view>
								</view>
								<view class="listItemInfo">
									<view class="listItemInfoLabel">律师标签：</view>
									<view class="listItemInfoValue">
										{{(item.lawyerTagList || []).map(tag => tag.name).join('、')}}
									</view>
								</view>

							</view>
						</z-paging>
					</view>
				</slot>
			</u-action-sheet>
		</view>
	</view>
</template>

<script>
	import {
		toast,
		clearStorageSync,
		getStorageSync,
		useRouter
	} from '@/utils/utils.js'
	export default {
		data() {
			return {
				selectedLawyers: [],
				searchKeyL: '',
				lawyerList: [],
				mapping: {},
				currentTab: {},
				currentIndex: 0,
				publishPreMsg: '',
				selectTime: null,
				showDelMappingModal: false,
				showPlanModal: false,
				showPublishPreModal: false,
				showReservationModal: false,
				showPublishTime: false,
				showGrabbingModal: false,
				showBookingModal: false,
				showLawyerModal: false,
				grabbingNumForm: {
					grabbingNum: 0,
				},
				rulesGrabbingNum: {
					grabbingNum: [{
						type: 'number',
						required: true,
						message: '抢班人数为正整数',
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							return uni.$u.test.digits(value);
						},
						trigger: ['blur', 'change']
					}]
				},
				showCloseModal: false,
				closeForm: {
					reason: '',
				},
				rulesCloseForm: {
					reason: [{
						type: 'string',
						min: 0,
						max: 255,
						required: true,
						message: '请输入关闭理由',
						trigger: ['blur', 'change']
					}]
				},
				reservationForm: {
					reason: '',
				},
				rulesReservationForm: {
					reason: [{
						type: 'string',
						min: 0,
						max: 255,
						required: true,
						message: '请输入取消理由',
						trigger: ['blur', 'change']
					}]
				},
				showPublishModal: false,
				publishForm: {
					publishType: '',
					publishTime: null
				},
				rulesPublishForm: {
					publishType: [{
						type: 'string',
						required: true,
						message: '请选择发布方式',
						trigger: ['change']
					}],
					publishTime: [{
						type: 'date',
						required: true,
						message: '请选择发布时间',
						trigger: ['change', 'blur']
					}]
				},
				tabs: [],
				selectTab: {},
				scrollTop: 0,
				dataList: [],
				icTypes: [],
				systemRoles: [],
				projectList: [],
				searchKey: '',
				currentNo: 0,
				total: 0,
				selectPlan: {}
			};
		},
		computed: {
			minDate: function() {
				return new Date().getTime()
			},
			isAdmin: function() {
				return (this.systemRoles || []).indexOf('admin') >= 0
			},
			hasOperationRole: function() {
				return (this.systemRoles || []).indexOf('OPERATION_MANAGER') >= 0 || (this.systemRoles || []).indexOf(
					'OPERATION') >= 0
			},
			hasLawyerM: function() {
				return (this.systemRoles || []).indexOf('LAWYER_MANAGER') >= 0
			},
		},
		methods: {
			initData: function() {
				this.dataList = []
				Promise.all([this.getSystemRoles(), this.getICTypes()]).then(val => {
					if (this.isAdmin || this.hasOperationRole) {
						this.tabs = [{
							name: '待发布',
							value: 'to_be_published'
						}, {
							name: '已发布',
							value: 'published'
						}]
					} else {
						this.tabs = [{
							name: '可预约',
							value: 'bookable'
						}, {
							name: '预约历史',
							value: 'history'
						}]
					}
					this.selectTab = this.tabs[0]
					this.currentIndex = 0
					this.$nextTick(() => {
						this.$refs.paging.reload(true);
					})
				})
			},
			getProjects: async function() {
				this.projectList = await this.$commonData.getProjects(false, {
					"containDel": true
				}) || []
			},
			getProjectName: function(valu) {
				let arr = this.projectList.filter(item => item.id == valu)
				if (arr && arr.length > 0) return arr[0].name
				return ''
			},
			getPercent: function(item) {
				if (item.currentNum == 0) return 0;
				if (item.grabbingNum == 0) return 100;
				return (item.currentNum / item.grabbingNum) * 100
			},
			showDate: function() {
				if (this.publishForm.publishTime) {
					this.selectTime = Number(new Date(this.publishForm.publishTime))
				} else {
					this.selectTime = new Date().getTime()
				}
				this.showPublishTime = true
				// #ifdef APP || MP
				uni.hideKeyboard()
				// #endif
			},
			confirmDate: function({
				value,
				mode
			}) {
				console.log(value, mode)
				if (value) {
					this.publishForm.publishTime = this.$moment(value).format('YYYY-MM-DD HH:mm:ss')
				} else {
					this.publishForm.publishTime = ''
				}
				this.showPublishTime = false
			},
			cancelDate: function() {
				this.showPublishTime = false
			},
			scroll() {
				if (this.$refs.backToTop) {
					this.$refs.backToTop.isScroll();
				}
			},
			getICTypes: async function() {
				this.icTypes = await this.$commonData.getICTypes()
			},
			getICType: function(val) {
				let arr = this.icTypes.filter(item => item.value == val)
				if (arr && arr.length > 0) return arr[0].label
				return ''
			},
			getTagLable: function(item) {
				let arr = this.icTypes.filter(icType => icType.value == item.schedulingPlanType)
				if (arr && arr.length > 0) return arr[0].label
				return '';
			},
			getSystemRoles: async function() {
				this.systemRoles = await this.$commonData.getSystemRoles()
			},
			changeTag: function(item) {
				console.log('changeTag', item)
				this.selectTab = Object.assign({}, item)
				//当切换tab或搜索时请调用组件的reload方法，请勿直接调用：queryList方法！！
				//调用reload时参数传true则代表reload时触发下拉刷新效果，不传或false则代表取消此效果
				this.$refs.paging.reload(true);
			},
			queryList(pageNo, pageSize) {
				// 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				// 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				// 模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageNo: pageNo,
					pageSize: pageSize,
					type: this.selectTab.value,
					searchKey: this.searchKey
				}
				this.$api.planList(params).then(res => {
					if (res.success) {
						let result = res.result || {}
						this.currentNo = pageNo
						this.total = result.maxPage || 0
						// 将请求的结果数组传递给z-paging
						this.$refs.paging.complete(result.data || []);
					} else {
						// 将请求的结果数组传递给z-paging
						toast(res.message)
						this.$refs.paging.complete(false);
					}
				}).catch(res => {
					// 如果请求失败写this.$refs.paging.complete(false);
					// 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
					// 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
					this.$refs.paging.complete(false);
				})
			},
			search: function() {
				this.$refs.paging.reload(true);
			},
			itemClick(item) {
				uni.navigateTo({
					url: './detail?id=' + item.id
				});
			},
			modifyGrabbingNum: function(item) {
				this.selectPlan = item
				this.grabbingNumForm.grabbingNum = item.grabbingNum || 0
				this.showGrabbingModal = true
				this.$nextTick(() => {
					this.$refs.grabbingNumForm.setRules(this.rulesGrabbingNum)
				})
			},
			confirmGrabbing() {
				let that = this
				this.$refs.grabbingNumForm.validate().then(async res => {
					if (res) {
						console.debug("Grabbing valid", res)
						if (this.selectPlan.grabbingNum != this.grabbingNumForm.grabbingNum) {
							this.$api.modifyGrabbingNum({
								planId: this.selectPlan.id,
								grabbingNum: this.grabbingNumForm.grabbingNum
							}).then(res => {
								if (res.success) {
									toast("修改成功！")
									this.selectPlan.grabbingNum = this.grabbingNumForm.grabbingNum
								} else {
									toast(res.message)
								}
							}).catch(err => {
								console.log("logout error", err)
								toast("修改抢班人数失败！")
							}).finally(() => {
								that.showGrabbingModal = false
							})
						} else {
							this.showGrabbingModal = false
						}
					} else {
						console.log('验证失败');
					}
				}).catch(e => {
					//TODO handle the exception
					console.error("confirmGrabbing validate error", e)
				})
			},
			closePlan: function(item) {
				this.selectPlan = item
				this.closeForm.reason = ''
				this.showCloseModal = true
				this.$nextTick(() => {
					this.$refs.closeForm.setRules(this.rulesCloseForm)
				})
			},
			confirmClose() {
				let that = this
				this.$refs.closeForm.validate().then(async res => {
					if (res) {
						console.debug("closeForm valid", res)
						this.$api.canceledPlan({
							planId: this.selectPlan.id,
							reason: this.closeForm.reason
						}).then(res => {
							if (res.success) {
								toast("关闭班次成功！")
								this.$refs.paging.reload(true);
							} else {
								toast(res.message)
							}
						}).catch(err => {
							console.log("logout error", err)
							toast("关闭班次失败！")
						}).finally(() => {
							that.showCloseModal = false
						})

					} else {
						console.log('验证失败');
					}
				}).catch(e => {
					//TODO handle the exception
					console.error("closeForm validate error", e)
				})
			},
			publishPlan: function(item) {
				this.selectPlan = item
				if (this.selectPlan.distributional) {
					//手动排班
					if (this.selectPlan.currentNum && this.selectPlan.currentNum > 0) {
						this.confirmPublishPre()
					} else {
						this.publishPreMsg = '当前班次' + this.selectPlan.planName + '人数为0， 请确认是否继续发布？'
						this.showPublishPreModal = true
					}
				} else {
					if (this.selectPlan.grabbingNum && this.selectPlan.grabbingNum > 0) {
						this.confirmPublishPre()
					} else {
						this.publishPreMsg = '当前班次' + this.selectPlan.planName + '抢班人数为0， 请确认是否继续发布？'
						this.showPublishPreModal = true
					}
				}
			},
			confirmPublishPre: function() {
				this.publishForm = {
					planIds: [],
					publishType: 'IMMEDIATE_RELEASE',
					publishTime: null
				}
				this.showPublishPreModal = false
				this.publishPreMsg = ''
				this.showPublishModal = true
				this.$nextTick(() => {
					this.$refs.publishForm.setRules(this.rulesPublishForm)
				})
			},
			confirmPublish() {
				let that = this
				this.$refs.publishForm.validate().then(async res => {
					if (res) {
						console.debug("publishForm valid", res)
						this.publishForm.planIds = [this.selectPlan.id]
						this.$api.publishPlan(this.publishForm).then(res => {
							if (res.success) {
								toast("发布班次成功！")
								this.$refs.paging.reload(true);
							} else {
								toast(res.message)
							}
						}).catch(err => {
							console.log("publishForm error", err)
							toast("发布班次失败！")
						}).finally(() => {
							that.showPublishModal = false
						})

					} else {
						console.log('验证失败');
					}
				}).catch(e => {
					//TODO handle the exception
					console.error("publishForm validate error", e)
				})
			},
			grabbingPlan: function(item) {
				this.selectPlan = item
				this.showBookingModal = true
			},
			confirmBooking() {
				let that = this
				this.$api.grabbingPlan({
					planId: this.selectPlan.id
				}).then(res => {
					if (res.success) {
						toast("预约成功！")
						this.$refs.paging.reload(true);
					} else {
						toast(res.message)
					}
				}).catch(err => {
					console.log("publishForm error", err)
					toast("预约失败！")
				}).finally(() => {
					that.showBookingModal = false
				})
			},
			cancelReservationPlan: function(item) {
				this.selectPlan = item
				this.showReservationModal = true
			},
			confirmReservation() {
				let that = this
				this.$refs.reservationForm.validate().then(async res => {
					if (res) {
						console.debug("reservationForm valid", res)
						this.reservationForm.planId = this.selectPlan.id
						this.$api.cancelReservationPlan(this.reservationForm).then(res => {
							if (res.success) {
								toast("取消成功！")
								this.$refs.paging.reload(true);
							} else {
								toast(res.message)
							}
						}).catch(err => {
							console.log("publishForm error", err)
							toast("取消失败！")
						}).finally(() => {
							that.showReservationModal = false
						})
					} else {
						console.log('验证失败');
					}
				}).catch(e => {
					//TODO handle the exception
					console.error("reservationForm validate error", e)
				})
			},
			viewPlan: function(item, change) {
				this.$api.planFullDetail({
					planId: item.id
				}).then(res => {
					if (res.success) {
						this.selectPlan = res.result || {}
						if (change) {
							this.currentTab = {
								name: '基础信息',
								value: 'base'
							}
						} else {
							// 需要修改列表下的当前总人数
							this.dataList.forEach(plan => {
								if (item.id == plan.id) {
									plan.currentNum = this.selectPlan.planRecruitMappings ? this.selectPlan.planRecruitMappings
										.length : 0
								}
							})
						}

						this.showPlanModal = true
					} else {
						toast(res.message)
					}
				}).catch(err => {
					toast("获取详情失败！")
				})
			},
			deleteMapping: function(mapping) {
				this.mapping = mapping
				this.showDelMappingModal = true
			},
			confirmDelMapping: function() {
				let that = this
				this.$api.delLawyerMapping({
					mappingId: this.mapping.id
				}).then(res => {
					if (res.success) {
						toast('删除成功!')
						that.viewPlan(this.selectPlan, false)
						this.showDelMappingModal = false
					} else {
						toast(res.message)
					}
				}).catch(err => {
					console.error('delLawyerMapping error', err)
					toast('删除失败！')
				}).finally(() => {
					that.showDelMappingModel = false
				})

			},
			addPerson: function(item) {
				this.selectPlan = item
				this.selectedLawyers = []
				this.showLawyerModal = true
				this.$nextTick(() => {
					this.$refs.lawyerPaging.reload(true);
				})
			},
			queryLawyerList(pageNo, pageSize) {
				// 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				// 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				// 模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageNo: pageNo,
					pageSize: pageSize,
					planId: this.selectPlan.id,
					searchKey: this.searchKeyL
				}
				this.$api.planLawyerList(params).then(res => {
					if (res.success) {
						let result = res.result || {}
						// 将请求的结果数组传递给z-paging
						this.$refs.lawyerPaging.complete(result.data || []);
					} else {
						// 将请求的结果数组传递给z-paging
						toast(res.message)
						this.$refs.lawyerPaging.complete(false);
					}
				}).catch(res => {
					// 如果请求失败写this.$refs.paging.complete(false);
					// 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
					// 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
					this.$refs.lawyerPaging.complete(false);
				})
			},
			searchL: function() {
				this.$refs.lawyerPaging.reload(true);
			},
			chooseLawyer: function(item) {
				let arr = this.selectedLawyers.filter(l => l.id == item.id)
				console.log('chooseLawyer', arr)
				if (arr && arr.length > 0) {
					// 存在 移除
					this.selectedLawyers = this.selectedLawyers.filter(l => l.id != item.id)
					this.$forceUpdate()
				} else {
					this.selectedLawyers.push(item)
				}
			},
			closeSelect: function(ind) {
				console.log('closeSelect', ind)
				this.selectedLawyers = this.selectedLawyers.filter(l => l.id != ind)
			},
			saveLawyer: function() {
				if (this.selectedLawyers.length == 0) {
					toast('请选择律师！')
				} else {
					this.$api.savePlanLawyers({
						planId: this.selectPlan.id,
						lawyerIds: this.selectedLawyers.map(item => item.id)
					}).then(res => {
						if (res.success) {
							toast('添加成功！')
							for (let item of this.dataList) {
								if (item.id == this.selectPlan.id) {
									item.currentNum = res.result
									break
								}
							}
						} else {
							toast(res.message)
						}
					}).catch(err => {
						console.log('saveLawyer error', err)
						toast('添加失败！')
					}).finally(() => {
						this.showLawyerModal = false
					})
				}
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		onTabItemTap() {
			console.log('onTabItemTap')
			this.initData()
		},
		onLoad: function(options) {
			this.getProjects()
			this.initData()
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		height: 100%;
		width: 100%;
		display: flex;
		flex-direction: column;
	}
</style>